package com.cdream.basic.algorithm.leetcode.dfs;

import com.hp.hpl.sparta.Document;

public class Offer12 {
    int m, n;

    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(board, word.toCharArray(), i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] word, int i, int j, int index) {
        if (i >= m || j >= n || i < 0 || j < 0) {
            return false;
        }
        if (word[index] != board[i][j]) {
            return false;
        }
        if (index == word.length - 1) {
            return true;
        }
        board[i][j] = '\0';
        boolean b = dfs(board, word, i + 1, j, index + 1) || dfs(board, word, i - 1, j, index + 1)
                || dfs(board, word, i, j + 1, index + 1) || dfs(board, word, i, j - 1, index + 1);
        board[i][j] = word[index];

        return b;
    }
}
